﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using Barry.BarbeSystem.Models;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Configuration = NHibernate.Cfg.Configuration;

namespace Barry.BarbeSystem
{
    public class NHibernateHelper
    {
        public static ISessionFactory CreateSessionFactory()
        {
            string server = ConfigurationManager.AppSettings["sqlServer"];
            string user = ConfigurationManager.AppSettings["user"];
            string pwd = ConfigurationManager.AppSettings["pwd"];
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(
                               c => c.Server(server)
                               .Database("barbersystem")
                               .Username(user)
                               .Password(pwd)))
                           .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DiscountModelMap>())
                           .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MemberMap>())
                           .Mappings(m => m.FluentMappings.AddFromAssemblyOf<BarberCategoryMap>())
                           .Mappings(m => m.FluentMappings.AddFromAssemblyOf<BarberDetailMap>())
                             .Mappings(m => m.FluentMappings.AddFromAssemblyOf<EmployeeMap>())
                              .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ConsumeHistoryMap>())
                           .ExposeConfiguration(CreateSchema)
                          
                           .BuildSessionFactory();
        }

        private static void CreateSchema(Configuration cfg)
        {
            SchemaUpdate chema = new SchemaUpdate(cfg);
            chema.Execute((x) => Console.WriteLine(x), true);

            
            //var schemaExport = new SchemaExport(cfg);
            //schemaExport.SetOutputFile("c:\\abc\\abc.sql");
            // schemaExport.Create(false, true);
        }


        private static ISession _session;

        public static ISession OpenSession()
        {
            if (_session == null)
            {
                var sessionFactory = CreateSessionFactory();
                _session = sessionFactory.OpenSession();
                return _session;
            }
            return _session;
        }
    }


    public class SqlStatementInterceptor:EmptyInterceptor
    {
        public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
        {
            //return base.OnPrepareStatement(sql);
            Trace.WriteLine(sql.ToString());
            return sql;
        }
    }
}